import paramiko

try:
    key = paramiko.RSAKey.from_private_key_file(pk_path)
except Exception, ex:
    print "%s"%(ex)
    sys.exit(1)


def sshcmd(ip, username, passwd, cmd, pk_path):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,username,passwd,timeout=5)
        for m in cmd:
            stdin, stdout, stderr = ssh.exec_command(m)
            out = stdout.readlines()
            for o in out:
                print o,
        print '%s\t0K\n'%(ip)
        ssh.close()
    except Exception,ex:
        print '%s\tError:%s,%s\n'%(ip,Exception,ex)
        pushrsa(ip,username,passwd,pk_path)

def pushrsa(ip,username,passwd,pk_path):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=hostname, username=username, password=passwd)
        file_open = open(pk_path + ".pub")
        try:
            rsapb = file_open.read( )
        finally:
            file_open.close( )
        stdin, stdout, stderr=ssh.exec_command('echo %s > /root/.ssh/authorized_keys'%(rsapb.strip('\n')))
        print stdout.readlines()
        print stderr.readlines()
        ssh.close()
    except Exception, ex:
        print "%s"%(ex)
    
if __name__ == '__main__':
    hostname = '192.168.181.43'
    username = 'root'
    password = '111111'
    pk_path = '/rdoot/.ssh/id_rsa'
    cmd = ['date']
    threads = []
    print "Begin work"
        pushrsa(ip,username,passwd,pk_path)
#for i in xxx:
#    t=threading.Thread(target=funciton)
#    t.start()
